
package com.hlkj.pay.controller.devices;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.common.util.collection.CollectionUtils;
import com.hlkj.pay.app.adminuser.IAdminUserAppService;
import com.hlkj.pay.app.devices.IMerchantQrAppService;
import com.hlkj.pay.common.CommonResultCode;
import com.hlkj.pay.controller.BaseController;
import com.hlkj.pay.dto.devices.MerchantQrDto;
import com.hlkj.pay.dto.devices.MerchantQrQueryDto;
import com.hlkj.pay.infrastructure.model.devices.MerchantQrDO;
import com.hlkj.pay.infrastructure.model.devices.MerchantQrSetDO;
import com.hlkj.pay.infrastructure.model.devices.MerchantQrTemplateDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantInfoDO;
import com.hlkj.pay.service.devices.IMerchantQrService;
import com.hlkj.pay.service.devices.IMerchantQrTemplateService;
import com.hlkj.pay.service.merchant.IMerchantService;
import com.hlkj.pay.util.DateUtils;
import com.hlkj.pay.vo.admin.resp.user.AdminUserDetailResp;
import com.hlkj.pay.vo.devices.req.MerchantQrBindReq;
import com.hlkj.pay.vo.devices.req.MerchantQrPageQueryReq;
import com.hlkj.pay.vo.devices.req.MerchantQrSetReq;
import com.hlkj.pay.vo.devices.req.MerchantQrUpdateReq;
import com.hlkj.pay.vo.devices.resp.MerchantQrDetailResp;
import com.hlkj.pay.vo.devices.resp.MerchantQrListResp;
import com.hlkj.pay.vo.devices.resp.MerchantQrTemplateResp;
import com.hlkj.pay.vo.merchant.req.UpdateStatusReq;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * @author HlpayTeam
 * @date 2025/01/20 11:03
 */
@Tag(name = "商户码牌管理")
@RestController
@RequestMapping("/v1/merchant/qr")
@RequiredArgsConstructor
public class MerchantQrController extends BaseController {

    private final IMerchantQrService merchantQrService;

    private final IMerchantQrAppService merchantQrAppService;

    private final IMerchantQrTemplateService merchantQrTemplateService;
    private final IMerchantService merchantService;
    private final IAdminUserAppService adminUserAppService;

    @Operation(summary = "商户码牌列表分页")
    @GetMapping("/page")
    CommonResult<PageResult<MerchantQrListResp>> queryPage(MerchantQrPageQueryReq merchantQrPageQueryReq) {
        MerchantQrQueryDto merchantQrQueryDto = BeanUtil.copyProperties(merchantQrPageQueryReq, MerchantQrQueryDto.class);
        processQueryDate(merchantQrPageQueryReq, merchantQrQueryDto);
        PageResult<MerchantQrDto> page = merchantQrService.queryPage(merchantQrQueryDto);
        List<MerchantQrDto> list = page.getList();
        if (CollectionUtils.isEmpty(list)) {
            return buildPageResult(page, Collections.emptyList());
        }
        List<MerchantQrListResp> merchantInfoPageResps = BeanUtil.copyToList(list, MerchantQrListResp.class);
        merchantInfoPageResps.forEach(merchantQr->{
            CommonResult<AdminUserDetailResp> adminUserDetailResp = adminUserAppService.userDetail(Long.valueOf(merchantQr.getCreatedBy())) ;
            if(adminUserDetailResp.isSuccess() && ObjectUtil.isNotEmpty(adminUserDetailResp.getData())){
                merchantQr.setCreatedByName(adminUserDetailResp.getData().getUserName());
            }
        });
        return buildPageResult(page, merchantInfoPageResps);
    }

    @Operation(summary = "商户码牌详情")
    @GetMapping("/detail")
    CommonResult<MerchantQrDetailResp> detailResp(@RequestParam(value = "code") String code) {
        MerchantQrDO merchantQrDO = merchantQrService.queryDetail(code);
        if (merchantQrDO == null) {
            return CommonResult.error(CommonResultCode.DATA_NOT_EXIST);
        }
        MerchantQrDetailResp merchantQrDetailResp = BeanUtil.copyProperties(merchantQrDO, MerchantQrDetailResp.class);
        MerchantQrSetDO merchantQrSetDO = merchantQrService.queryDetailSet(merchantQrDO.getBatchNo());
        if (merchantQrSetDO != null) {
            MerchantQrTemplateDO merchantQrTemplateDO = merchantQrTemplateService.queryDetail(merchantQrSetDO.getTemplateId());
            if (merchantQrTemplateDO != null) {
                merchantQrDetailResp.setMerchantQrTemplateResp(BeanUtil.copyProperties(merchantQrTemplateDO, MerchantQrTemplateResp.class));
            }
            merchantQrDetailResp.setTemplateId(merchantQrSetDO.getTemplateId());
            merchantQrDetailResp.setNum(merchantQrSetDO.getNum());
            merchantQrDetailResp.setPageType(merchantQrSetDO.getPageType());
        }
        if(StringUtils.hasText(merchantQrDO.getSn())){
            MerchantInfoDO merchantInfoDO = merchantService.queryMerchant(merchantQrDO.getSn());
            if (merchantInfoDO != null) {
                merchantQrDetailResp.setShortName(merchantInfoDO.getShortName());
                merchantQrDetailResp.setMerchantName(merchantInfoDO.getName());
                merchantQrDetailResp.setSn(merchantInfoDO.getSn());
            }
        }
        return CommonResult.success(merchantQrDetailResp);
    }

    @Operation(summary = "商户码牌批次号生成")
    @GetMapping("/batchNo")
    CommonResult<String> batchNo() {
        MerchantQrQueryDto merchantQrQueryDto = new MerchantQrQueryDto();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startOfDay = now.withHour(0).withMinute(0).withSecond(0).withNano(1);
        merchantQrQueryDto.setStartQueryTime(DateUtils.shanghaiDate(startOfDay));
        merchantQrQueryDto.setEndQueryTime(DateUtils.shanghaiDate(startOfDay.plusDays(1)));
        merchantQrQueryDto.setPageNo(1);
        merchantQrQueryDto.setPageSize(1);
        //查询所有
        merchantQrQueryDto.setFilterSn(false);
        PageResult<MerchantQrDto> page = merchantQrService.queryPage(merchantQrQueryDto);
        List<MerchantQrDto> list = page.getList();
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.success(DateUtils.dateToString(merchantQrQueryDto.getStartQueryTime(), "yyMMdd") + "001");
        }
        MerchantQrDto merchantQrDto = list.get(0);
        String batchNo = merchantQrDto.getBatchNo();
        String end = batchNo.substring(6);
        String yyyyMMdd = batchNo.substring(0, 6);
        return CommonResult.success(yyyyMMdd + String.format("%03d", (Integer.parseInt(end) + 1)));
    }

    @Operation(summary = "商户码牌保存")
    @PostMapping("")
    CommonResult<Void> saveQr(@Validated @RequestBody MerchantQrSetReq merchantQrSetReq) {
        return merchantQrAppService.saveQr(merchantQrSetReq);
    }

    @Operation(summary = "商户码牌更新")
    @PutMapping("")
    CommonResult<Void> updateQr(@Validated @RequestBody MerchantQrUpdateReq merchantQrSetReq) {
        return merchantQrAppService.updateQr(merchantQrSetReq);
    }

    @Operation(summary = "商户码牌绑定")
    @PostMapping("/bind")
    CommonResult<Void> bindQr(@Validated @RequestBody MerchantQrBindReq merchantQrBindReq) {
        return merchantQrAppService.bindQr(merchantQrBindReq);
    }

    @Operation(summary = "商户码牌更新状态")
    @PostMapping("/status")
    CommonResult<Void> updateStatus(@Validated @RequestBody UpdateStatusReq updateStatusReq) {
        return merchantQrAppService.updateStatus(updateStatusReq);
    }
}
